'use strict';

const { Gateway,Wallets} = require('fabric-network');
const path = require('path');
const { getCurrentDate,buildCCPOrg3, buildWallet } = require('../../../jsUtils/AppUtil.js');

const channelName = 'channel2';
const chaincodeName = 'basic';

const walletPathOrg3 = path.join(__dirname, 'walletOrg3');

const org3d1 = 'org3repo';
const org3d2 = 'org3transfer';

const goods=['apple','banana','orange','pear'];


function prettyJSONString(inputString) {
	return JSON.stringify(JSON.parse(inputString));
}

//消费者通过org3公司购买物品
//后端创建交易
exports.createLedgerOrg3=async (ledger)=>{
	//ledger为JSON数组
	try{
		const ccp = buildCCPOrg3();
		const wallet = await buildWallet(Wallets, walletPathOrg3);
		const gateway = new Gateway();
		
		try {
			await gateway.connect(ccp, {
				wallet,
				identity: org3d1,
				discovery: { enabled: true, asLocalhost: true }
			});
			const network = await gateway.getNetwork(channelName);
			const contract = network.getContract(chaincodeName);
			console.log('\n--> Submit Transaction: CreateAssetA, creates new asset with ID, amount, owner, price, and time arguments');
			
            var arrayResult=new Array();
			for(var i=0;i<ledger.length;i++){
				var date=getCurrentDate();
				let result = await contract.submitTransaction('CreateAsset', ledger[i].id,goods[i],ledger[i].amount,'org3repo',ledger[i].price,date);
				console.log('*** Result: committed');
				if (`${result}` !== '') {
					console.log(`*** Result: ${prettyJSONString(result.toString())}`);
					arrayResult.push(result.toString());
				}
			}

      		return arrayResult;//返回值为字符串
		} finally {
			gateway.disconnect();
		}
	}
	catch(error){
		console.error(`FAILED to run the application: ${error}`);
	}	
}

//org3货物运输到中转站，中转站进行确认
exports.org3Repo2Transfer=async (ledger)=>{
	/**
	 * ledger=[
	 * 		{
	 * 			id:10,
	 * 			amount:100,
	 * 			price:200
	 * 		},
	 * 		...
	 * ]
	 */
	try{
		const ccp = buildCCPOrg3();
		const wallet = await buildWallet(Wallets, walletPathOrg3);
		const gateway = new Gateway();

		try {
			await gateway.connect(ccp, {
				wallet,
				identity: org3d2,
				discovery: { enabled: true, asLocalhost: true }
			});
			const network = await gateway.getNetwork(channelName);
			const contract = network.getContract(chaincodeName);
			
            var arrayResult=new Array();
			for(var i=0;i<ledger.length;i++){
				console.log('\n--> Submit Transaction: TransferAsset, transfer to new owner of org3transfer');
				var date=getCurrentDate();
				let result=await contract.submitTransaction('TransferAsset', ledger[i], 'org3transfer',date);
				console.log('*** Result: committed');
				if (`${result}` !== '') {
					console.log(`*** Result: ${prettyJSONString(result.toString())}`);
					arrayResult.push(result.toString());
				}
			}
            return arrayResult;
		} finally {
			gateway.disconnect();
		}
	}
	catch(error){
		console.error(`FAILED to run the application: ${error}`);
	}	
}
